﻿@page "/"
@inject UserBasket _basket
@inject CatalogClient _catalogClient
@inject Settings _settings

<section class="esh-catalog-filters">
    <div class="container">

        @if (_error != null)
        {
            <div class="alert" role="alert">
                Error requesting catalog items, please try later. @_error
            </div>
        }

        <div class="esh-catalog-filters-wrapper d-flex align-items-end mt-3">
            <div class="esh-catalog-filter-wrapper">
                <label class="esh-catalog-label" for="brand">Brand</label>
                <select class="esh-catalog-filter form-control" id="brand" @onchange=@OnBrandChangedAsync>
                    @foreach (var brand in _brands)
                    {
                        <option value=@brand.Id>@brand.Name</option>
                    }
                </select>
            </div>
            <div class="esh-catalog-filter-wrapper">
                <label class="esh-catalog-label" for="type">Type</label>
                <select class="esh-catalog-filter form-control" id="type" @onchange=@OnTypeChangedAsync>
                    @foreach (var type in _types)
                    {
                        <option value=@type.Id>@type.Name</option>
                    }
                </select>
            </div>
        </div>
    </div>
</section>

<div class="container">
    @if (_catalogPage?.Count > 0)
    {
        <Pager ItemCount="@_catalogPage.Items.Count()"
            TotalCount="@_catalogPage.Count"
            PageIndex="@_catalogPage.PageIndex"
            PageCount="@_catalogPage.PageCount"
            OnClick="OnPageIndexChangedAsync"/>

        <div class="esh-catalog-items row">
            @foreach (var item in _catalogPage.Items)
            {
                <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                    <div class="esh-catalog-item @(!_isAuthenticated ? "is-disabled" : "")" @onclick="@(e => OnCatalogItemClickAsync(item))">
                        <div class="esh-catalog-thumbnail-wrapper">
                            <div class="esh-catalog-thumbnail-icon d-flex justify-content-center">
                                <img class="esh-catalog-thumbnail-icon-svg" src="images/add.svg" />
                            </div>
                            <img class="esh-catalog-thumbnail" src="@item.GetPictureUrl(_settings)" />
                        </div>
                        <div class="esh-catalog-details d-flex justify-content-between align-items-center">
                            <div class="esh-catalog-name ml-3">
                                <span>@item.Name</span>
                            </div>
                            <div class="esh-catalog-price mr-3">
                                <span>@item.GetFormattedPrice()</span>
                            </div>
                        </div>
                    </div>
                </div>
            }
        </div>

        <Pager ItemCount="@_catalogPage.Items.Count()"
            TotalCount="@_catalogPage.Count"
            PageIndex="@_catalogPage.PageIndex"
            PageCount="@_catalogPage.PageCount"
            OnClick="OnPageIndexChangedAsync"/>
    }
    else if (_catalogPage != null)
    {
        <h2>THERE ARE NO RESULTS THAT MATCH YOUR SEARCH</h2>
    }
</div>

@code {
    private CatalogPage? _catalogPage;
    private IEnumerable<CatalogBrand> _brands = Enumerable.Empty<CatalogBrand>();
    private IEnumerable<CatalogType> _types = Enumerable.Empty<CatalogType>();

    private int _pageIndex = 0;
    private int _brandId = -1;
    private int _typeId = -1;

    private bool _isAuthenticated;
    private string? _error;

    [CascadingParameter]
    private Task<AuthenticationState> _authenticationStateTask { get; set; } = null!;

    protected override async Task OnInitializedAsync()
    {
        await Task.WhenAll(
            LoadBrandsAsync(),
            LoadTypesAsync(),
            LoadItemsAsync(),
            _authenticationStateTask.ContinueWith(task =>
            {
                _isAuthenticated = task!.Result!.User!.Identity!.IsAuthenticated;
            }));
    }

    public async Task OnPageIndexChangedAsync(int newPageIndex)
    {
        _pageIndex = newPageIndex;

        await LoadItemsAsync();
    }

    private async Task OnBrandChangedAsync(ChangeEventArgs e)
    {
        _brandId = int.Parse(e.Value!.ToString()!);
        _pageIndex = 0;

        await LoadItemsAsync();
    }

    private async Task OnTypeChangedAsync(ChangeEventArgs e)
    {
        _typeId = int.Parse(e.Value!.ToString()!);
        _pageIndex = 0;

        await LoadItemsAsync();
    }

    private async Task OnCatalogItemClickAsync(CatalogItem item)
    {
        if (_isAuthenticated)
        {
            try
            {
                await _basket.AddItemAsync(item);
            }
            catch (AccessTokenNotAvailableException ex)
            {
                ex.Redirect();
            }
        }
    }

    private async Task LoadBrandsAsync()
    {
        var brands = new List<CatalogBrand>
        {
            new CatalogBrand(-1, "All")
        };

        try
        {
            brands.AddRange(await _catalogClient.GetBrandsAsync());
        }
        catch
        {
            // If call fails, we'll just have the 'All' selection.
        }

        _brands = brands;
    }

    private async Task LoadTypesAsync()
    {
        var types = new List<CatalogType>
        {
            new CatalogType(-1, "All")
        };

        try
        {
            types.AddRange(await _catalogClient.GetTypesAsync());
        }
        catch
        {
            // If call fails, we'll just have the 'All' selection.
        }

        _types = types;
    }

    private async Task LoadItemsAsync()
    {
        try
        {
            _catalogPage = await _catalogClient.GetItemsAsync(_brandId, _typeId, _pageIndex);
            _error = null;
        }
        catch (Exception ex)
        {
            _catalogPage = null;
            _error = ex.Message;
        }
    }
}
